import json

import requests
import json
import re
def dify_chat_streaming(query,data_event,api_key):
    # API端点和API密钥
    # url = 'http://172.16.32.45:11206/v1/chat-messages' #v1/chat-messages'调用聊天框  workflows/run智能体
    url = 'http://192.168.73.129:80/v1/chat-messages' #v1/chat-messages'调用聊天框  workflows/run智能体
    # api_key = 'app-poRofzsvJiJGhpc1Wn1ecEbg'  # 替换为您的实际API密钥

    # 请求头
    headers = {
        'Authorization': f'Bearer {api_key}',
        'Content-Type': 'application/json'
    }

    # 请求数据
    data = {
        "inputs": {},
        "query": query,
        "response_mode": "streaming", #blocking streaming
        "conversation_id": "",
        "user": "abc-123",
            }

    # 将数据转换为JSON字符串
    data_json = json.dumps(data)

    # 发送POST请求
    # response = requests.post(url, headers=headers, data=data_json.encode("utf-8"))
    # response.encoding = 'utf-8'

    answer = ''

    # 发送GET请求，并设置stream=True
    with requests.post(url, headers=headers, data=data_json.encode("utf-8"), stream=True) as r:
        # 检查请求是否成功
        r.raise_for_status()
        print('r',r)
        # if '200'in r:
        #     print(json.loads(r.text))
        # 打印每一行文本
        for line in r.iter_lines():
            # 忽略保持连接的空行
            if line:
                print(line)
                # 解码每一行，因为返回的数据可能是字节串
                line = line.decode('utf-8')
                if 'data: ' in line:
                    data = json.loads(line.replace('data: ', ''))
                    if data['event'] == data_event:
                        print(data['answer'],end='')
                        answer += data['answer']
    return answer
# print(dify_chat_streaming('你好',data_event='agent_message',api_key = 'app-poRofzsvJiJGhpc1Wn1ecEbg'))
# json_statement= dify_chat_streaming('你好', data_event='message', api_key='app-kq9Bj0KXAPNjYKUyZd0gNoYJ')
